package top.dotgo.web.base;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.lang.NonNull;
import top.dotgo.kit.ds.DynamicDataSourceContextHolder;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author jornl
 * @date 2020/2/5 23:32 星期三
 */
public class DynamicDataSource extends AbstractRoutingDataSource {

    private static final Map<Object, Object> DATA_SOURCE_MAP = new HashMap<>(5);
    private static DynamicDataSource instance;
    private static Properties defaultConnectProperties;

    public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources, Properties connectProperties) {
        super.setDefaultTargetDataSource(defaultTargetDataSource);
        setTargetDataSources(targetDataSources);
        defaultConnectProperties = connectProperties;
        instance = this;
    }

    private static synchronized DynamicDataSource getInstance() {
        return instance;
    }

    /***
     * 添加数据源
     * @param dbTag dbTag
     * @param url url
     * @param user user
     * @param password password
     * @return {@link boolean}
     * @author jornl
     * @date 2020/2/6 18:30
     */
    public static synchronized boolean addDataSource(String dbTag, String url, String user, String password) {
        try {
            DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
            dataSource.setConnectProperties(defaultConnectProperties);
            dataSource.setUrl(url);
            dataSource.setUsername(user);
            dataSource.setPassword(password);
            Map<Object, Object> tempMap = new HashMap<>(DATA_SOURCE_MAP);
            tempMap.put(dbTag, dataSource);
            getInstance().setTargetDataSources(tempMap);
            return true;
        } catch (Exception ex) {
            return false;
        }

    }

    @Override
    public void setTargetDataSources(@NonNull Map<Object, Object> targetDataSources) {
        super.setTargetDataSources(targetDataSources);
        DATA_SOURCE_MAP.clear();
        DATA_SOURCE_MAP.putAll(targetDataSources);
        // 必须添加该句，否则新添加数据源无法识别到
        super.afterPropertiesSet();
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return DynamicDataSourceContextHolder.getDataSourceType();
    }
}
